<template>
  <div>
    {{ ruleForm.type[2] }}
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="商品分类" prop="type">
        <el-cascader :placeholder="placeholder" v-model="ruleForm.type" :props="props" />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>

      <el-form-item label="商品简介" prop="desc">
        <el-input v-model="ruleForm.desc" type="textarea" />
      </el-form-item>

      <el-form-item label="商品价格" prop="price">
        <el-input v-model="ruleForm.price" type="number" />
      </el-form-item>
      <el-form-item label="商品售卖价" prop="salesprice">
        <el-input v-model="ruleForm.salesprice" type="number" />
      </el-form-item>
      <el-form-item label="商品库存" prop="store">
        <el-input v-model="ruleForm.store" type="number" />
      </el-form-item>
      <el-form-item label="商品标签" prop="flag">
        <el-input v-model="ruleForm.flag" />
      </el-form-item>

      <el-form-item label="商品状态" prop="resource">
        <el-radio-group v-model="ruleForm.resource">

          <el-radio value="0">上架</el-radio>
          <el-radio value="1">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="图片" prop="imageUrl">
        <el-upload class="avatar-uploader" action="http://backend-api-02.newbee.ltd/manage-api/v1/upload/file"
          :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
          :headers="{ Token }">
          <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <!-- 富文本 -->
      <el-form-item label="商品详情" prop="content">
        <editor-vue :content="ruleForm.content" :readOnlys="readOnlys" @changeData="hChangeData"
          @uploadImg="hUploadImg" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          {{route.query.id?"修改":"添加"}}
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>









  </div>
</template>

<script setup>
let Token = localStorage.getItem("token");

import editorVue from '../../components/compon.vue'
import { ref, reactive, onMounted, computed } from "vue"
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router';
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios';
let readOnlys = ref(false)
let router = useRouter()
let route = useRoute()
let placeholder = ref("请选择分类")
const hChangeData = (editDataHtml) => {
  // console.log(editDataHtml);
  // 获取最新的html数据
  ruleForm.content = editDataHtml
  // console.log(content)
}
const hUploadImg = async(file, insertFn) => {
  console.log(file)
  let formDatas=FormData()
  formDatas.append("file",file)
  // 插入图片，调接口返回图片url,通过插入conteng
  let res =await axios.post('/upload/files',formDatas,{
    headers:{
    'Content-Type' : 'application/x-www-form-urlencoded'
  }
  }
 
)
  // let imgUrl = 'https://img1.baidu.com/it/u=608404415,1639465523&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800'
  insertFn(res[0]);

  // 设置只读
  // this.readOnlys = true;
}

let id = ref(0)
// 下面是获取商品信息
onBeforeRouteUpdate(() => {
  console.log("路由更新");
  ruleForm.type = ""

})
onMounted(() => {

  if (route.query.id) {
    id.value = route.query.id

    getid(route.query.id)

  }
})

let getid = async (id) => {
  let { firstCategory, secondCategory, thirdCategory, goods } = await axios.get(`/goods/${id}`, {

  })
  ruleForm.type = [firstCategory.categoryId, secondCategory.categoryId, thirdCategory.categoryId] //分类
  ruleForm.name = goods.goodsName //名称
  ruleForm.desc = goods.goodsIntro //商品简介
  ruleForm.price = goods.originalPrice //商品价格
  ruleForm.salesprice = goods.sellingPrice //商品售卖价格
  ruleForm.store = goods.stockNum //库存
  ruleForm.flag = goods.tag //商品标签
  ruleForm.imageUrl = goods.goodsCoverImg
  ruleForm.resource = goods.goodsSellStatus.toString()
  ruleForm.content = `${goods.goodsDetailContent}` //富文本编辑器数据
  placeholder.value = `${firstCategory.categoryName}/${secondCategory.categoryName}/${thirdCategory.categoryName}`
}
// 以上是富文本

const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = reactive({
  type: "", //分类
  name: "", //名称
  desc: "", //商品简介
  price: "", //商品价格
  salesprice: "", //商品售卖价格
  store: "", //库存
  flag: "", //商品标签
  imageUrl: "",
  resource: "0", //上架下架状态
  content: "", //富文本编辑器数据
})

const rules = reactive({
  type: [
    { required: true, message: '商品分类', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '商品名称', trigger: 'blur' },

  ],

  desc: [
    { required: true, message: '商品简介', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '商品价格', trigger: 'blur' },

  ],
  salesprice: [
    { required: true, message: '商品售卖价格', trigger: 'blur' },
  ],
  store: [
    { required: true, message: '库存', trigger: 'blur' },
  ],
  flag: [
    { required: true, message: '商品标签', trigger: 'blur' },

  ],
  resource: [
    { required: true, message: '上架下架状态', trigger: 'blur' },

  ],
  imageUrl: [
    { required: true, message: '图片', trigger: 'blur' },

  ],

})

const submitForm = async (formEl) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {

    if (valid) {
      if (route.query.id) {
        getdata("put")
        title.value = '修改'
      } else {
        getdata("post")//增加


      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

let getdata = async (method) => {

  let obj = {
    goodsCategoryId: ruleForm.type[2],
    goodsCoverImg: ruleForm.imageUrl,
    goodsDetailContent: ruleForm.content,
    goodsIntro: ruleForm.desc,
    goodsName: ruleForm.name,
    goodsSellStatus: ruleForm.resource,
    originalPrice: ruleForm.price,
    sellingPrice: ruleForm.salesprice,
    stockNum: ruleForm.store,
    tag: ruleForm.flag,
  }
  if (method == "put") {
    obj.goodsId = id.value
  }
  let res = await axios({
    url: '/goods',
    method,
    data: obj
  })
  router.push({
    name: "goods",
    query: {
      categoryLevel: 1,
      parentId: 0
    }
  })
}


//图片
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  console.log(response);
  ruleForm.imageUrl = response.data
}


const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
//分类
const props = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level, value } = node

    let { list } = await axios.get("/categories", {
      params: {
        pageNumber: 1,
        pageSize: 1000,
        categoryLevel: level + 1,
        parentId: level == 0 ? 0 : value,
      },
    });

    const nodes = []

    list.map((item) => {
      nodes.push({
        value: item.categoryId,
        label: item.categoryName,
        leaf: level >= 2,
      });
    })
    // setTimeout(() => {
    //   const nodes = Array.from({ length: level + 1 }).map((item) => ({
    //     value: ++id,
    //     label: `Option - ${id}`,
    //     leaf: level >= 2,
    //   }))
    //   // Invoke `resolve` callback to return the child nodes data and indicate the loading is finished.
    //   resolve(nodes)
    // }, 1000)
    resolve(nodes)
  },
}
</script>
<style lang="scss">
.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #999;
  line-height: 100px;
  text-align: center;
  font-size: 50px;
  color: #999;

  img {
    width: 100px;
    height: 100px;
  }
}
</style>